﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Outlook.WorkItems.Extension.Managers;

namespace Outlook.WorkItems.Extension.Manager
{
    /// <summary>
    /// Manager of Favorites Team Projects
    /// </summary>
    public class FavoritesTeamProjectManager
    {
        /// <summary>
        /// File Path that contains Link Information between MAPIFolder and Team Project
        /// </summary>
        private static readonly string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OWIPlugin\\FavoritesTeamProject.owi";
        /// <summary>
        /// List of Favorites Team Project
        /// </summary>
        private static readonly List<FavoriteTeamProject> Favorites;

        /// <summary>
        /// Static Constructor
        /// </summary>
        static FavoritesTeamProjectManager()
        {
            Favorites = new List<FavoriteTeamProject>();

            if (File.Exists(AppDataFolder))
            {
                XDocument xdoc = XDocument.Load("file:///" + AppDataFolder);

                bool saveFavorites = false;
                foreach (var item in xdoc.Root.Elements("FavoriteProject"))
                {
                    FavoriteTeamProject ftp = new FavoriteTeamProject()
                    {
                        TeamServerName = item.Attribute("teamServerName").Value,
                        TeamProjectName = item.Attribute("teamProjectName").Value,
                        IsDefault = Convert.ToBoolean(item.Attribute("isDefault").Value),
                        RServerAlternativeAddress = item.Attribute("rServerAlternativeAddress").Value,
                        RServiceAlternativeAddress = item.Attribute("rServiceAlternativeAddress").Value,
                        WssAlternativeAddress = item.Attribute("wssAlternativeAddress").Value
                    };

                    var atts = item.Attributes("teamServerUri");
                    if (atts != null && atts.Count() == 1)
                        ftp.TeamServerUri = atts.ToList()[0].Value;
                    else
                    {
                        try
                        {
                            WorkItemStore store = new WorkItemStore(ftp.TeamServerName);

                            ftp.TeamServerUri = store.TeamProjectCollection.Uri.ToString();
                            saveFavorites = true;
                        }
                        catch { }
                    }

                    Favorites.Add(ftp);
                }

                if (saveFavorites)
                    SaveFavorites();
            }
        }

        /// <summary>
        /// Returns Default Favorite
        /// </summary>
        /// <returns></returns>
        public static FavoriteTeamProject GetDefaultTeamProject()
        {
            return (from ftp in Favorites
                    where ftp.IsDefault
                    select ftp).FirstOrDefault();
        }

        /// <summary>
        /// Define specified Favorite as Default
        /// </summary>
        /// <param name="ftp"></param>
        public static void DefineAsDefault(FavoriteTeamProject ftp)
        {
            foreach (var item in Favorites)
            {
                item.IsDefault = false;
            }
            ftp.IsDefault = true;

            SaveFavorites();
        }

        /// <summary>
        /// Save on disk All Favorites
        /// </summary>
        private static void SaveFavorites()
        {
            string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OWIPlugin";
            if (Directory.Exists(appFolder) == false)
            {
                Directory.CreateDirectory(AppDataFolder);
            }

            XDocument xdoc;
            if (File.Exists(AppDataFolder))
            {
                xdoc = XDocument.Load("file:///" + AppDataFolder);
                xdoc.Root.RemoveAll();
            }
            else
            {
                xdoc = new XDocument(new XElement("FavoritesProjects"));
            }
            foreach (var ftp in Favorites)
            {
                xdoc.Root.Add(new XElement("FavoriteProject",
                                            new XAttribute("teamServerName", ftp.TeamServerName),
                                            new XAttribute("teamServerUri", ftp.TeamServerUri),
                                            new XAttribute("teamProjectName", ftp.TeamProjectName),
                                             new XAttribute("wssAlternativeAddress", ftp.WssAlternativeAddress),
                                            new XAttribute("rServerAlternativeAddress", ftp.RServerAlternativeAddress),
                                            new XAttribute("rServiceAlternativeAddress", ftp.RServiceAlternativeAddress),
                                           new XAttribute("isDefault", ftp.IsDefault)));
            }
            xdoc.Save(AppDataFolder);
        }

        /// <summary>
        /// Returns All Favorites
        /// </summary>
        /// <returns></returns>
        public static List<FavoriteTeamProject> GetFavoritesProjects()
        {
            return Favorites;
        }

        /// <summary>
        /// Add Favorite
        /// </summary>
        /// <param name="ftp"></param>
        public static void AddFavoriteProject(FavoriteTeamProject ftp)
        {
            string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OWIPlugin";
            if (Directory.Exists(appFolder) == false)
            {
                Directory.CreateDirectory(appFolder);
            }

            XDocument xdoc = null;
            if (File.Exists(AppDataFolder))
            {
                xdoc = XDocument.Load("file:///" + AppDataFolder);
            }
            else
            {
                xdoc = new XDocument(new XElement("FavoritesProjects"));
            }
            xdoc.Root.Add(new XElement("FavoriteProject",
                            new XAttribute("teamServerName", ftp.TeamServerName),
                            new XAttribute("teamServerUri", ftp.TeamServerUri),
                            new XAttribute("teamProjectName", ftp.TeamProjectName),
                            new XAttribute("wssAlternativeAddress", ftp.WssAlternativeAddress),
                            new XAttribute("rServerAlternativeAddress", ftp.RServerAlternativeAddress),
                            new XAttribute("rServiceAlternativeAddress", ftp.RServiceAlternativeAddress),
                            new XAttribute("isDefault", ftp.IsDefault)));

            xdoc.Save(AppDataFolder);

            Favorites.Add(ftp);
        }

        /// <summary>
        /// Remove Favorite
        /// </summary>
        /// <param name="ftp"></param>
        public static void RemoveFavoriteProject(FavoriteTeamProject ftp)
        {
            XDocument xdoc = null;
            if (File.Exists(AppDataFolder))
            {
                xdoc = XDocument.Load("file:///" + AppDataFolder);
                var ftpFind = (from elt in xdoc.Root.Elements("FavoriteProject")
                               where elt.Attribute("teamServerName").Value == ftp.TeamServerName && elt.Attribute("teamProjectName").Value == ftp.TeamProjectName
                               select elt).FirstOrDefault();
                if (ftpFind != null)
                {
                    ftpFind.Remove();

                    Favorites.Remove(ftp);
                    xdoc.Save(AppDataFolder);

                }
            }
        }
    }
}